package com.mzpai.web.controller;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.mzpai.product.constant.OrderConstants;
import com.mzpai.product.constant.PayConstants;
import com.mzpai.product.constant.WXCommonConstants;
import com.mzpai.product.enums.OrderStatusEnum;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.model.Express;
import com.mzpai.product.model.StoreOrder;
import com.mzpai.product.model.StoreOrderCartInfo;
import com.mzpai.product.model.SystemStore;
import com.mzpai.product.model.User;
import com.mzpai.product.model.UserBindStore;
import com.mzpai.product.model.WstPayments;
import com.mzpai.product.service.ExpressService;
import com.mzpai.product.service.StoreOrderCartInfoService;
import com.mzpai.product.service.StoreOrderService;
import com.mzpai.product.service.SystemStoreService;
import com.mzpai.product.service.UserBindStoreService;
import com.mzpai.product.service.UserService;
import com.mzpai.product.service.WstPaymentsService;
import com.mzpai.product.util.ImageMergeUtil;
import com.mzpai.product.util.WxQrCodeUtil;
import com.mzpai.product.vo.ShareStoreInfoVo;
import com.mzpai.product.vo.StoreCashierAccountReqVo;
import com.mzpai.product.vo.StoreCashierSucessVo;
import com.mzpai.product.vo.StoreOfflinePayOrderVo;
import com.mzpai.product.vo.StoreOnlinePayOrderVo;
import com.mzpai.product.vo.StoreOrderVo;
import com.mzpai.vo.ResponseVo;
import com.mzpai.web.utils.StorageUploadUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
 *
 * <b>订单列表 | Controller</b><br>
 *
 * yanglijun 2021-04-09 23:51:49
 * 
 *  @version 1.0.0
 *
 */
@Api(value = "订单数据接口")
@RestController
@RequestMapping("/storeOrder")
public class StoreOrderController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(StoreOrderController.class);
	
	@Autowired 
	private StoreOrderService storeOrderService;
	@Autowired 
	private ExpressService expressService;
	@Autowired 
	private StoreOrderCartInfoService storeOrderCartInfoService;
	@Autowired
	private WstPaymentsService wstPaymentsService;
	@Autowired
	private UserService userService;
	@Autowired 
	private SystemStoreService systemStoreService;
	
	private static String DEFULT_USER_TEXT="202108061931";
	
	@Autowired
	private UserBindStoreService userBindStoreService;
	
	
	/** 
	*
	* 查询列表 
	* @throws Exception
	* "0","待付款"
		"1","待发货"
		"2","待自提"
		"3","已发货"
		"4","已完成"
		"5","已取消"
	*/
	@ApiOperation(value = "根据条件分页查询订单数据； status == 0,待付款，1,待发货，2,待自提，3,已发货，4,已完成，5,已取消")
	@RequestMapping("/getPageList")
	@ResponseBody
	public ResponseVo<PageInfo<StoreOrderVo>> getPageList(@RequestParam("storeId") String storeId, @RequestParam("status") String status,
			@RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize) throws Exception {
		logger.info("msg1=获取门店订单参数storeId={}，status={}，pageNum={}，pageSize={}", storeId, status,pageNum,pageSize);
		ResponseVo<PageInfo<StoreOrderVo>> res = new ResponseVo<PageInfo<StoreOrderVo>>();
		try{
			if (StringUtils.isBlank(storeId)){
				throw new IllegalArgumentException("storeId不能为空!");
			}
			if (pageNum < 0 || pageSize < 0){
				throw new IllegalArgumentException("pageNum | pageSize 不能小于0!");
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("storeId", storeId);
			addProductStatus(status, map);
			PageInfo<StoreOrderVo> pageInfo = storeOrderService.getVoListPage(map , pageNum, pageSize);
			List<StoreOrderVo> list = pageInfo.getList();
			for(StoreOrderVo o : list) {
				List<StoreOrderCartInfo> productList = storeOrderCartInfoService.getListByOrderId(o.getId());
				o.setAttrValueList(productList);
				o.setSubPrice(o.getTotalPrice().subtract(o.getPayPrice()));
				String orderType=o.getOrderType();
				String payType=o.getPayType();
				if(StringUtils.isNotBlank(payType) && "weixin".equals(payType)){
					o.setPayType("微信支付");
				}
				if(StringUtils.isNotBlank(orderType) && OrderConstants.ORDER_TYPE_1.equals(orderType)){
					o.setOrderType("网店订单");
				}else if(StringUtils.isNotBlank(orderType) && OrderConstants.ORDER_TYPE_2.equals(orderType)){
					o.setOrderType("门店订单");
				}else{
					o.setOrderType("其它");
				}
				
				addOrderStatus(o);
			}
			res.setResult(pageInfo);
		} catch(Exception e) {
			logger.error("msg1=获取订单列表异常!");
			res.setCode(-1);
			res.setMessage("获取订单列表异常");
		}
		return res;
	}
	
	/**
	 * 设置订单状态
	 * @param o
	 */
	private void addOrderStatus(StoreOrderVo o) {
		
		if("1".equals(o.getIsDel())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_5.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_5.getCode());
		} else if("2".equals(o.getStatus())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_4.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_4.getCode());
		}  else if("0".equals(o.getPaid())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_0.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_0.getCode());
		} else if("1".equals(o.getPaid()) && "0".equals(o.getStatus()) && "1".equals(o.getShippingType())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_1.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_1.getCode());
		} else if("0".equals(o.getStatus()) && "2".equals(o.getShippingType())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_2.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_2.getCode());
		} else if("1".equals(o.getStatus()) && "1".equals(o.getShippingType())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_3.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_3.getCode());
		}else if("1".equals(o.getPaid()) && "3".equals(o.getStatus()) && "2".equals(o.getShippingType())) {
			o.setStatusName(OrderStatusEnum.getTitle(OrderStatusEnum.ORDER_STATUS_4.getCode()));
			o.setStatus(OrderStatusEnum.ORDER_STATUS_4.getCode());
		}
	}

	/** 
	*
	*更新快递发货接口
	* @throws Exception
	*/
	@ApiOperation(value = "更新快递发货接口")
	@RequestMapping(value = "/addExpressInfo")
	@ResponseBody
	public ResponseVo<Boolean> addExpressInfo(@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "expressId", required = true) String expressId,
			@RequestParam(value = "deliveryId", required = true) String deliveryId) throws Exception {
		logger.info("msg=更新快递发货接口参数 id ={}, expressId={},deliveryId={} ", id, expressId, deliveryId);
		ResponseVo<Boolean> resp = new ResponseVo<Boolean>();
		try{
			Express express = expressService.queryById(expressId);
			StoreOrder target = new StoreOrder();
			target.setId(Integer.parseInt(id));
			target.setDeliveryId(deliveryId);
			target.setDeliveryType("express");
			target.setDeliveryName(express.getName());
			target.setStatus(1);
			storeOrderService.update(target);
			resp.setResult(true);
		} catch(Exception e) {
			resp.setCode(-1);
			resp.setMessage("更新快递信息失败!");
		}
		return resp;
	}
	
	
	
	/** 
	*
	*订单核销接口
	* @throws Exception
	*/
	@ApiOperation(value = "订单核销接口")
	@RequestMapping(value = "/addComplateOrder")
	@ResponseBody
	public ResponseVo<Boolean> addComplateOrder(@RequestParam(value = "id", required = true) String id) throws Exception {
		logger.info("msg=更新快递发货接口参数 id ={} ", id);
		ResponseVo<Boolean> resp = new ResponseVo<Boolean>();
		try{
			StoreOrder target = new StoreOrder();
			target.setId(Integer.parseInt(id));
			target.setStatus(2);
			storeOrderService.update(target);
			resp.setResult(true);
		} catch(Exception e) {
			resp.setCode(-1);
			resp.setMessage("订单核销接口失败!");
		}
		return resp;
	}
	
	/**
	 *  status == 0,待付款，1,待发货，2,待自提，3,已发货，4,已完成，5,已取消；
	 * @param status
	 * @param map
	 */
	private void addProductStatus(String status, Map<String, Object> map) {
		map.put("isDel", "0");
		switch (status) {
		case "0":
			map.put("paid", "0");
			break;
		case "1":
			map.put("paid", "1");
			map.put("status", "0");
			map.put("shippingType", "1");
			break;
		case "2":
			map.put("paid", "1");
			map.put("status", "0");
			map.put("shippingType", "2");
			break;
		case "3":
			map.put("paid", "1");
			map.put("shippingType", "1");
			map.put("status", "1");
			break;
		case "4":
			map.put("status", "2");
			/*List<Integer> statusList=new ArrayList<Integer>();
			statusList.add(2);
			statusList.add(3);
			map.put("statusList", statusList);*/
			
			break;
		case "5":
			map.put("isDel", "1");
			break;
		default:
			break;
		}
	}

	
	
	
	/**
	 * @author guguanfei
	 * @param queryProductByPageStr
	 * @return
	 */
	@ApiOperation(value = "门店收银结算接口")
    @RequestMapping(value = "/storeCashierAccount",method = {RequestMethod. POST})
    public ResponseVo<StoreCashierSucessVo> storeCashierAccount(
    		@ApiParam(required = true, name = "storeCashierAccountStr", value = "入参为storeCashierAccountStr")
    		@RequestParam(value = "storeCashierAccountStr", required = true) String storeCashierAccountStr){
	
		log.info("msg1=开始分门店收银结算接口,,method=storeCashierAccount,,reqVo={}",storeCashierAccountStr);
		StoreCashierAccountReqVo cshierAccountReqVo = JSONObject.parseObject(storeCashierAccountStr, StoreCashierAccountReqVo.class);
		
		Integer storeId=cshierAccountReqVo.getStoreId();
		String userEncryptData=cshierAccountReqVo.getUserEncryptData();
//		String signData=cshierAccountReqVo.getUserSignData();
		Long dateTime=cshierAccountReqVo.getCurrentDateTime();
		
		//支付方式,0:到店付款; 1:线上收款
		String payMethod = cshierAccountReqVo.getPayMethod();
		String payCode = cshierAccountReqVo.getPayCode();
		
		
		SystemStore systemStore=systemStoreService.queryByPrimaryId(storeId);
		String qrcodeShareImage=systemStore.getWechatappletQrcodeShareImage();
		
		String lastMergImageUrl=null;
		
		if(StringUtils.isBlank(qrcodeShareImage)){
			//门店信息
			String storeName=systemStore.getName();
			String logoImage=systemStore.getImage();
			//获取门店小程序二维码
			String token=null;
			try {
				token = WxQrCodeUtil.postToken(WXCommonConstants.appId, WXCommonConstants.AppSecret);
			} catch (Exception e) {
				e.printStackTrace();
				ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
				resVo.setCode(ProductResExceptionCode.GET_TOKEN_ERROR.getCode());
				resVo.setMessage(ProductResExceptionCode.GET_TOKEN_ERROR.getMessage());
				return resVo;
			}
			 
			 String scene="storeId="+storeId;
			 InputStream in=WxQrCodeUtil.generateQrCode("pages/store/storeDetail/storeDetail", scene, token);
			 
			 BufferedImage qrCodeBufferImage = null;
			 try {
				qrCodeBufferImage = ImageIO.read(in);
			} catch (IOException e) {
				e.printStackTrace();
				ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
				resVo.setCode(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getCode());
				resVo.setMessage(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getMessage());
				return resVo;
			}
			 
//	        String logoUrl="https://thirdwx.qlogo.cn/mmopen/vi_32/gjEcX8W0yxtN2mbhY7MuyYdOCUbyAnZjCpmY2VhG7PBZK8a8G7JiajmTCKBHjERtsxgEY9zR7icKpYbZbTV9ASGA/132";
	        String logoUrl=logoImage;
	        BufferedImage newsunImage=ImageMergeUtil.replaceSunCodeLogo (qrCodeBufferImage,logoUrl);
	        
	        //bufferedimage 转换成 inputstream
	        ByteArrayOutputStream bs = new ByteArrayOutputStream();
			try {
				ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
				ImageIO.write(newsunImage, "jpg", imOut);
			    InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
			    lastMergImageUrl=StorageUploadUtil.ossUploadFile(inputStream, "jpg");
			} catch (Exception e) {
				e.printStackTrace();
				ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
				logger.error("msg1=生成门店分享二维码失败,,method=queryShareStoreInfo");
				resVo.setCode(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getCode());
				resVo.setMessage(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getMessage());
				return resVo;
			}
	        logger.info("msg1=分享店铺信息,聚合图片路径,,method=queryShareStoreInfo,,lastMergImageUrl={}",lastMergImageUrl);
	        
	        ShareStoreInfoVo shareStoreInfoVo=new ShareStoreInfoVo();
			shareStoreInfoVo.setQrcodeShareImage(lastMergImageUrl);
			SystemStore updateSystemStore=new SystemStore();
			updateSystemStore.setId(storeId);
			updateSystemStore.setWechatappletQrcodeShareImage(lastMergImageUrl);
			systemStoreService.update(updateSystemStore);
		}else{
			lastMergImageUrl=qrcodeShareImage;
		}
		
		/**
		 * 参数校验提出方法 TO DO
		 */
		if(storeId==null){
			ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
			resVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			return resVo;
		}
		
		//没有扫描用户会员则默认访客 设置默认访客订单类型
		String orderType=null;
		if(StringUtils.isBlank(userEncryptData)){
			userEncryptData=DEFULT_USER_TEXT;
			orderType=OrderConstants.ORDER_TYPE_3;
		}
		
		if(StringUtils.isBlank(userEncryptData)){
			ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
			resVo.setCode(ProductResExceptionCode.USER_ENCRYPT_DATA_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.USER_ENCRYPT_DATA_NULL.getMessage());
			return resVo;
		}
		
//		DEFULT_USER_TEXT
		
        /*if(StringUtils.isBlank(signData)){
        	ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
			resVo.setCode(ProductResExceptionCode.USER_SIGN_DATA_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.USER_SIGN_DATA_NULL.getMessage());
			return resVo;
		}*/

		if(StringUtils.isBlank(payMethod)){
			ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
			resVo.setCode(ProductResExceptionCode.PAY_METHOD_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.PAY_METHOD_NULL.getMessage());
			return resVo;
		}
        
		if(StringUtils.isBlank(payCode)){
			ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
			resVo.setCode(ProductResExceptionCode.PAY_CODE_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.PAY_CODE_NULL.getMessage());
			return resVo;
		}
		
        User user=userService.queryByUserText(userEncryptData);
        
        if(user==null){
        	ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
			resVo.setCode(ProductResExceptionCode.USER_INFO_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.USER_INFO_NULL.getMessage());
			return resVo;
        }
        
        if(!userEncryptData.equals(DEFULT_USER_TEXT)){
        	Integer userId=user.getUid();
            Map<String,Object> mapUserBindStore=new HashMap<String,Object>();
            mapUserBindStore.put("userId", userId);
            mapUserBindStore.put("storeId", storeId);
            //校验用户是否为该门店用户
            List<UserBindStore> listUserBindStore=userBindStoreService.getList(mapUserBindStore);
            if(listUserBindStore==null || listUserBindStore.isEmpty()){
            	ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
    			resVo.setCode(ProductResExceptionCode.NOT_BIND_USE.getCode());
    			resVo.setMessage(ProductResExceptionCode.NOT_BIND_USE.getMessage());
    			return resVo;
            }
        }
        
        
        //校验用户是否是这个门店的
        
        WstPayments wstPayments=wstPaymentsService.queryByPayCode(payCode);
        String orderId=null;
        
        //到店付款
        if(PayConstants.IS_OFFLINE_PAY.equals(payMethod)){
        	StoreOfflinePayOrderVo storeOfflinePayOrderVo=storeOrderService.createStoreOfflinePayOrder(cshierAccountReqVo,user,wstPayments,orderType);
        	orderId=storeOfflinePayOrderVo.getOrderId();
        }else{
        	StoreOnlinePayOrderVo storeOnlinePayOrderVo=storeOrderService.createStoreOnlinePayOrder(cshierAccountReqVo, user, wstPayments,orderType);
        	orderId=storeOnlinePayOrderVo.getOrderId();
        }
		/**
		 * 设置返回值
		 */
		StoreCashierSucessVo storeCashierSucessVo=new StoreCashierSucessVo();
		storeCashierSucessVo.setOrderId(orderId);
		ResponseVo<StoreCashierSucessVo> resVo=new ResponseVo<StoreCashierSucessVo>();
		resVo.setResult(storeCashierSucessVo);
		log.info("msg1=结束分门店收银结算接口,,method=storeCashierAccount");
    	return resVo;
    }
	
	
	/** 
	*
	* 查询列表 
	* @throws Exception
	* "0","待付款"
		"1","待发货"
		"2","待自提"
		"3","已发货"
		"4","已完成"
		"5","已取消"
	*/
	@ApiOperation(value = "根据条件分页查询当前商户下，当前用户下所有订单数据")
	@RequestMapping("/getStoreAndUserIdPageList")
	@ResponseBody
	public ResponseVo<PageInfo<StoreOrderVo>> getStoreAndUserIdPageList(@RequestParam("storeId") String storeId, @RequestParam("userId") String userId,
			@RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize) throws Exception {
		logger.info("msg1=获取门店订单参数storeId={}，userId={}，pageNum={}，pageSize={}", storeId, userId,pageNum,pageSize);
		ResponseVo<PageInfo<StoreOrderVo>> res = new ResponseVo<PageInfo<StoreOrderVo>>();
		try{
			if (StringUtils.isBlank(storeId)){
				throw new IllegalArgumentException("storeId不能为空!");
			}
			if (pageNum < 0 || pageSize < 0){
				throw new IllegalArgumentException("pageNum | pageSize 不能小于0!");
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("storeId", storeId);
			map.put("userId", userId);
			PageInfo<StoreOrderVo> pageInfo = storeOrderService.getVoListPage(map , pageNum, pageSize);
			List<StoreOrderVo> list = pageInfo.getList();
			for(StoreOrderVo o : list) {
				List<StoreOrderCartInfo> productList = storeOrderCartInfoService.getListByOrderId(o.getId());
				o.setAttrValueList(productList);
				String orderType=o.getOrderType();
				String payType=o.getPayType();
				if(StringUtils.isNotBlank(payType) && "weixin".equals(payType)){
					o.setPayType("微信支付");
				}
				if(StringUtils.isNotBlank(orderType) && OrderConstants.ORDER_TYPE_1.equals(orderType)){
					o.setOrderType("网店订单");
				}else if(StringUtils.isNotBlank(orderType) && OrderConstants.ORDER_TYPE_2.equals(orderType)){
					o.setOrderType("门店订单");
				}else{
					o.setOrderType("其它");
				}
				
				addOrderStatus(o);
			}
			res.setResult(pageInfo);
		} catch(Exception e) {
			logger.error("msg1=获取订单列表异常!");
			res.setCode(-1);
			res.setMessage("获取订单列表异常");
		}
		return res;
	}

}